<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    form
    :width="700"
    :model-value="modelValue"
    :title="isUpdate ? '编辑用户' : '新增用户'"
    @update:model-value="updateModelValue"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
      <el-row :gutter="16">
        <el-col :sm="12" :xs="24">
          <el-form-item label="头像" prop="thumb">
            <ImageUpload
              v-model="form.thumb"
              :item-style="imageUploadItemStyle"
              :button-style="imageUploadItemStyle"
              :limit="1"
            />
          </el-form-item>
        </el-col>
        <el-col :sm="12" :xs="24">
          <el-form-item label="备注信息">
            <el-input v-model="form.desc" type="textarea" :rows="3" :maxlength="200" placeholder="请输入备注信息" />
          </el-form-item>
        </el-col>

        <el-col :sm="12" :xs="24">
          <el-form-item label="平台名称" prop="name">
            <el-input v-model="form.name" clearable :maxlength="20" placeholder="请输入平台名称" />
          </el-form-item>
          <el-form-item label="登录账号" prop="username">
            <el-input v-model="form.username" clearable :maxlength="20" placeholder="请输入登录账号" />
          </el-form-item>
          <el-form-item label="登录密码" prop="pwd" :required="!isUpdate">
            <el-input v-model="form.pwd" show-password type="password" :maxlength="20" :placeholder="isUpdate ? '✱✱✱✱✱✱' : '请输入登录密码'" />
          </el-form-item>

          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status" placeholder="请选择状态">
              <el-radio label="正常" :value="1" />
              <el-radio label="禁用" :value="2" />
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :sm="12" :xs="24">
          <el-form-item label="用户名" prop="nickname">
            <el-input v-model="form.nickname" clearable :maxlength="20" placeholder="请输入用户名(昵称)" />
          </el-form-item>

          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="form.mobile" clearable :maxlength="11" placeholder="请输入手机号" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" clearable :maxlength="100" placeholder="请输入邮箱" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="updateModelValue(false)">
        取消
      </el-button>
      <el-button type="primary" :loading="loading" @click="save">
        保存
      </el-button>
    </template>
  </ele-modal>
</template>

<script setup>
import { updateMch } from '@/api/system/mch'
import { pageRole } from '@/api/system/role'
import ImageUpload from '@/components/ImageUpload/index.vue'
import { emailReg, phoneReg } from 'ele-admin-plus/es'
import { reactive, ref, watch } from 'vue'

const props = defineProps({
  /** 弹窗是否打开 */
  modelValue: Boolean,
  /** 修改回显的数据 */
  data: Object,
})

const emit = defineEmits(['done', 'update:modelValue'])

/** 是否是修改 */
const isUpdate = computed(() => form.id > 0)

const roleList = ref([])

pageRole({ is_all: 1 }).then((res) => {
  roleList.value = res.list
})

const imageUploadItemStyle = { width: '80px', height: '80px', margin: 0 }

/** 提交状态 */
const loading = ref(false)

/** 表单实例 */
const formRef = ref(null)

/** 表单数据 */
const { form, resetFields, assignFields } = utils.useFormData({
  id: undefined,
  thumb: undefined,
  username: '',
  nickname: '',
  name: [],
  email: '',
  mobile: '',
  pwd: '',
  desc: '',
  status: 1,
})

/** 表单验证规则 */
const rules = reactive({
  nickname: [{ required: true, message: '请输入用户名/昵称', type: 'string', trigger: 'blur' }],
  name: [{ required: true, message: '请输入平台名称', type: 'string', trigger: 'blur' }],
  email: [{ pattern: emailReg, message: '邮箱格式不正确', type: 'string', trigger: 'blur' }],
  username: [
    { required: true, message: '请输入登录帐号', type: 'string', trigger: 'blur' },
    { min: 4, message: '账号长度最少为4位', type: 'string', trigger: 'blur' },

  ],
  pwd: [
    { required: true, message: '请输入登录密码', type: 'string', trigger: 'blur' },
    { type: 'string', trigger: 'blur', validator: (_rule, value, callback) => {
      if ((isUpdate.value && value === '') || /^\S{5,18}$/.test(value))
        return callback()

      callback(new Error('密码必须为5-18位非空白字符'))
    } },
  ],
  mobile: [
    { required: true, message: '请输入手机号', type: 'string', trigger: 'blur' },
    { pattern: phoneReg, message: '手机号格式不正确', type: 'string', trigger: 'blur' },
  ],
})

/** 保存编辑 */
function save() {
  formRef.value?.validate?.((valid) => {
    if (!valid)
      return

    loading.value = true
    updateMch(form)
      .then((res) => {
        utils.message(res.msg, res.success)
        if (res.success) {
          updateModelValue(false)
          emit('done')
        }
      })
      .finally(() => {
        loading.value = false
      })
  })
}

/** 更新modelValue */
function updateModelValue(value) {
  emit('update:modelValue', value)
}

watch(
  () => props.modelValue,
  (modelValue) => {
    if (modelValue) {
      if (props.data) {
        assignFields({
          ...props.data,
          pwd: '',
        })
      }
    }
    else {
      resetFields()
      formRef.value?.clearValidate?.()
    }
  },
)
</script>
